package repository

import (
	"go-web/config"
	"go-web/model"
)

func FindAllUsers() ([]model.User, error) {
	var users []model.User
	err := config.DB.Find(&users).Error
	return users, err
}

func FindUserByID(id int) (model.User, error) {
	var user model.User
	err := config.DB.First(&user, id).Error
	return user, err
}

func CreateUser(user *model.User) error {
	return config.DB.Create(user).Error
}

func UpdateUser(user *model.User) error {
	return config.DB.Save(user).Error
}

func DeleteUser(id int) error {
	return config.DB.Delete(&model.User{}, id).Error
}

func FindUsersPaged(page, size int) ([]model.User, int64, error) {
	var users []model.User
	var total int64

	offset := (page - 1) * size
	query := config.DB.Model(&model.User{})

	if err := query.Count(&total).Error; err != nil {
		return users, 0, err
	}

	err := query.Offset(offset).Limit(size).Find(&users).Error

	return users, total, err
}

func SearchUsers(name, email string, page, size int) ([]model.User, int64, error) {

	var users []model.User
	var total int64

	offset := (page - 1) * size
	query := config.DB.Model(&model.User{})

	if name != "" {
		query = query.Where("name LIKE ?", "%"+name+"%")
	}
	if email != "" {
		query = query.Where("email LIKE ?", "%"+email+"%")
	}

	if err := query.Count(&total).Error; err != nil {
		return users, 0, err
	}

	err := query.Offset(offset).Limit(size).Find(&users).Error

	return users, total, err
}
